package com.whsxt.sys.service.impl;

import com.whsxt.common.util.ConstantUtil;
import com.whsxt.sys.domain.Permission;
import com.whsxt.sys.domain.Role;
import com.whsxt.sys.mapper.PermissionMapper;
import com.whsxt.sys.mapper.RoleMapper;
import com.whsxt.sys.service.IRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 贺炯
 * @since 2019-09-24
 */
@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
	
	@Autowired
	private PermissionMapper permissionMapper;
	
	/**
	 * 根据角色id 查询该角色拥有的权限
	 */
	@Override
	public List<Permission> selectPermissionByRid(Integer rid) {
		List<Integer> list = this.getBaseMapper().selectPidByRid(rid);
		List<Permission> selectList = null;
		if(list.size()>0) {
			QueryWrapper<Permission> queryWrapper = new QueryWrapper<Permission>();
			queryWrapper.eq("available", ConstantUtil.AVAILABLE_TRUE);
			queryWrapper.in("id", list);
			selectList = permissionMapper.selectList(queryWrapper);
		}else {
			selectList = new ArrayList<Permission>();
		}
		return selectList;
	}
	/**
	 * 保存权限
	 */
	@Override
	public void savePidByRid(Integer rid, Integer[] pid) {
		//先删除角色之前拥有的权限
		this.getBaseMapper().deletePidByRid(rid);
		//if(pid != null && pid.length >0) {
			//for (Integer id : pid) {
				//再插入角色赋予的权限
			//	this.getBaseMapper().insertPidByRid(rid,id);
		//	}
		//}
		//批量插入	
		if(rid != null && pid!= null &&pid.length>0) {
			this.getBaseMapper().savePid(rid,pid);
		}
	}
	/**
	 *  根据用户id 查询 角色id
	 */
	@Override
	public List<Integer> selectRidByUid(Integer id) {
		 List<Integer> ridList = this.getBaseMapper().selectRidByUid(id);
		return ridList;
	}
	/**
	 *  向用户角色表中 插入数据    
	 *  插入之前先删除原来的数据
	 */
	@Override
	public void insertRidUid(Integer uid, Integer[] rid) {
		this.getBaseMapper().deleteUidRidByUid(uid);
		if(rid!=null&&uid!=null&&rid.length>0) {
			this.getBaseMapper().insertUidRid(uid,rid);
		}
		
	}
	/**
	 * 根据 角色id 查询对应的权限id
	 */
	@Override
	public List<Integer> selectPidByRid(List<Integer> roleList) {
		List<Integer> pidList = null;
		if(roleList != null && roleList.size()>0) {
			pidList =  this.getBaseMapper().ListPidByRid(roleList);
		}
		return pidList;
	}

}
